package com.gamesnet.api;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Hashtable;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class Request {
	//private final String CONTEXT = "http://10.0.2.2:8080/Gamesnet/api/";
	
	private final String CONTEXT = "http://10.0.2.2:8080/Gamesnet/api/";
	private Hashtable<String, String> params;
	private String target;

	public Request(String target){
		params = new Hashtable<String, String>();
		this.target = target;
	}

	public void addParameters(String name, String value){
		params.put(name, value);
	}

	public JSONObject send(){	
		try {
			HttpClient client = new DefaultHttpClient();
			
			String request = buildRequest();
			Log.v("API request", request);
			HttpGet get = new HttpGet(request);
			HttpResponse response;

			response = client.execute(get);
			HttpEntity entity = response.getEntity();

			if(entity != null){
				InputStream instream = entity.getContent();
				String result = convertStreamToString(instream);
				Log.v("API result requets", result);
				JSONObject json=new JSONObject(result);

				return json;
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return null;
	}

	private String buildRequest(){
		String request = CONTEXT + target ;

		for (Entry<String, String> param : params.entrySet()) {
			

			request += "/"+param.getValue();

		}

		return request;
	}

	private String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
}
